import axios, { AxiosInstance } from 'axios'
import { session } from '@/service/storage.service'


// axios 请求方式枚举
enum METHOD {
  GET = 'GET',
  DELETE = 'DELETE',
  HEAD = 'HEAD',
  OPTIONS = 'OPTIONS',
  POST = 'POST',
  PUT = 'PUT',
  PATCH = 'PATCH',
  PURGE = 'PURGE',
  LINK = 'LINK',
  UNLINK = 'UNLINK'
}
export { METHOD }

enum STATUS {
  SUCCESS = 'ok',
  FAIL = 'fail'
}

/**
 * 构建axios实例并增加拦截器
 * @author WangLiZhi
 * @param baseURL
 * @param config
 * @returns AxiosInstance
 */
function create(baseURL = '', config = {}): AxiosInstance {
  // 初始化axios实例
  const http = axios.create({
    timeout: 30000, // 设置超时
    baseURL: baseURL, // 设置统一接口地址
    // headers: {
    //   'Content-Type': 'application/json;charset=UTF-8;' // 设置内容数据格式和编码
    // },
    ...config
  })

  /**
   * 请求拦截器
   * 1.添加token到header上
   */
  http.interceptors.request.use(
    (config) => {
      // http header上添加token
      // const token = session.get(VITE_STORAGE_TOKEN)
      // token && (config.headers.Authorization = token)
      return config
    },
    (error) => Promise.reject(error)
  )

  // 响应拦截白名单
  const whiteList = [200, 201]
  /**
   * 响应拦截器
   * 1.响应数据格式化
   * 2.请求错误处理
   */
  http.interceptors.response.use(
    (response) => {
      if (whiteList.includes(response.status)) {
       
        return Promise.resolve(response)
      }
      return Promise.reject(response)
    },
    (error) => {
      const status = error?.response?.status
      if (status) {
        let message
        switch (status) {
          case 400:
            message = '请求错误!'
            break
          case 401:
            message = '请求错误!'
            break
          case 404:
            message = '此刻无数据!'
            break
          case 408:
            message = '请求超时!'
            break
          case 500:
            message = '服务器内部错误!'
            break
          case 501:
            message = '服务未实现!'
            break
          case 502:
            message = '网关错误!'
            break
          case 503:
            message = '服务不可用!'
            break
          case 504:
            message = '网关超时!'
            break
          case 505:
            message = 'HTTP版本不受支持!'
            break
          default:
            message = '请求失败!'
        }
      }
      return Promise.reject(error)
    }
  )
  return http
}

// 创建请求接口的axios实例
export const request = create()
